package com.menqui.localizame.Gps;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.location.Location;
import android.os.Environment;
import android.util.Log;

public class GpsFichero {
	private String LOG_TAG = getClass().toString();
	private String name = "";
	private Context context = null;
	private File fichero = null;
	private Integer lastPosition = 0;

	public GpsFichero(Context context) {
		name = String.valueOf((new Date()).getTime()) + ".mqg";
		this.context = context;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			  File path = Environment.getExternalStoragePublicDirectory(
			            Environment.DIRECTORY_DCIM);

			  fichero = new File(path, name);
		}
	}

	public void setLocalizacion(Location location) {
		if (location != null){
			String cadena = location.getTime() + ";" +
							location.getLatitude() + ";" +
							location.getLongitude() + ";" +
							location.getAltitude() + ";" +
							location.getBearing() + ";" +
							location.getSpeed() + ";" +
							location.getProvider() + ";" +
							location.getAccuracy()
							+ "\n";
	
			try {
				FileOutputStream fos = null;
				if (fichero != null) {
					fos = new FileOutputStream(fichero,true);
				} else {
					fos = context.openFileOutput(name, Context.MODE_APPEND);
				}
	
				fos.write(cadena.getBytes());
				fos.close();
			} catch (IOException e) {
				Log.w(LOG_TAG, "Error writing " + name, e);
			}
		}
	}

	public List<Location> getLastLocations() {
		InputStream fos = null;
		List<Location> resultado = new ArrayList<Location>();
		try {
			if (fichero != null) {
				fos = new FileInputStream(fichero);
			} else {
				fos = context.openFileInput(name);
			}

			 if (fos != null) {
			      // prepare the file for reading
			      InputStreamReader inputreader = new InputStreamReader(fos);
			      BufferedReader buffreader = new BufferedReader(inputreader);

			      String line = buffreader.readLine();

			      // read every line of the file into the line-variable, on line at the time
			      Integer contador = 0;
			      while (( line != null)) {
			    	  if (contador >= lastPosition) {
			    		  Location location = calcularLocation(line);
			    		  resultado.add(location);
			    	  }
			    	  line = buffreader.readLine();
			    	  contador ++;
			      }

			    }
			fos.close();
		} catch (IOException e) {
			Log.w(LOG_TAG, "Error leyendo fichero " + name, e);
		}
		return resultado;
	}

	public void actualizarIndice(Integer numero) {
		lastPosition += numero;
	}
	private Location calcularLocation(String line) {
		String[] opciones = line.split(";");
		Location location = new Location("");

		location.setTime(Long.parseLong(opciones[0]));
		location.setLatitude(Double.parseDouble(opciones[1]));
		location.setLongitude(Double.parseDouble(opciones[2]));
		location.setAltitude(Double.parseDouble(opciones[3]));
		location.setBearing(Float.parseFloat(opciones[4]));
		location.setSpeed(Float.parseFloat(opciones[5]));
		location.setProvider(opciones[6]);
		location.setAccuracy(Float.parseFloat(opciones[7]));
		return location;
	}
}
